import React, { PureComponent } from 'react';
import { findDOMNode } from 'react-dom';
import { connect } from 'dva';
import { List, Card, Input, Button, InputNumber, Avatar, Modal, Form } from 'antd';
import * as math from 'mathjs';
import { imageOrigin } from '../config';
import ImageUploader from '@/components/ImageUploader';
import ImagesUploader from '@/components/ImagesUploader';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import Result from '@/components/Result';
import styles from './Commodity.less';

const FormItem = Form.Item;
const { Search } = Input;

@connect(({ commodity, loading }) => ({
  commodity,
  loading: loading.models.list,
}))
@Form.create()
class Commodity extends PureComponent {
  state = {
    visible: false,
    done: false,
    previewVisible: false,
    previewImage: '',
  };

  formLayout = {
    labelCol: { span: 7 },
    wrapperCol: { span: 13 },
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'commodity/fetch',
    });
  }

  showModal = () => {
    this.setState({
      visible: true,
      current: undefined,
    });
  };

  handleCancels = () => this.setState({ previewVisible: false });

  handlePreview = file => {
    this.setState({
      previewImage: file.url || file.thumbUrl,
      previewVisible: true,
    });
  };

  showEditModal = (item, index) => {
    this.setState({
      visible: true,
      current: item,
      editableIndex: index,
    });
  };

  handleDone = () => {
    setTimeout(() => this.addBtn.blur(), 0);
    this.setState({
      done: false,
      visible: false,
    });
  };

  handleCancel = () => {
    setTimeout(() => this.addBtn.blur(), 0);
    this.setState({
      visible: false,
    });
  };

  isOnSelect = value => {
    if (value !== 'present') {
      this.setState({});
    } else {
      this.setState({});
    }
  };

  handleSubmit = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    const { current, editableIndex } = this.state;
    const id = current ? current.id : '';
    setTimeout(() => this.addBtn.blur(), 0);
    Math.formatInt = f => {
      const m = math.eval(f * 100);
      return math.round(m);
    };
    form.validateFields((err, fieldsValue) => {
      const price = Math.formatInt(fieldsValue.price);
      const original = Math.formatInt(fieldsValue.original);
      if (err) return;
      this.setState({
        done: true,
      });
      if (id) {
        dispatch({
          type: 'commodity/update',
          payload: {
            ...fieldsValue,
            itemType: 'commodities',
            price,
            id,
            original,
            editableIndex,
          },
        });
      } else {
        dispatch({
          type: 'commodity/add',
          payload: {
            ...fieldsValue,
            itemType: 'commodities',
            price,
            original,
            status: 'offshelf',
          },
        });
      }
    });
  };

  deleteItem = (id, currentIndex) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'commodity/remove',
      payload: { id, currentIndex },
    });
  };

  handleSearch = value => {
    const { dispatch } = this.props;
    dispatch({
      type: 'commodity/search',
      payload: value,
    });
  };

  render() {
    const {
      commodity: { data },
      loading,
    } = this.props;
    const {
      form: { getFieldDecorator },
    } = this.props;
    const { visible, done, previewVisible, previewImage, current = {} } = this.state;
    const editAndDelete = (currentItem, currentIndex) => {
      Modal.confirm({
        title: '删除任务',
        content: '确定删除该任务吗？',
        okText: '确认',
        cancelText: '取消',
        onOk: () => this.deleteItem(currentItem.id, currentIndex),
      });
    };
    const modalFooter = done
      ? { footer: null, onCancel: this.handleDone }
      : { okText: '保存', onOk: this.handleSubmit, onCancel: this.handleCancel };

    const ListContent = ({ data: { price, original, status, detail, unit } }) => (
      <div className={styles.listContent}>
        <div className={styles.listContentItem}>
          <span>价格</span>
          <p>{price / 100}</p>
        </div>
        <div className={styles.listContentItem}>
          <span>原价</span>
          <p>{original / 100}</p>
        </div>
        <div className={styles.listContentItem}>
          <span>状态</span>
          <p>{status === 'offshelf' ? '待售' : '在售'}</p>
        </div>
        <div className={styles.listContentItem}>
          <span>商品单位</span>
          <p>{unit || '暂无'}</p>
        </div>
        <div className={styles.listContentItem}>
          <span>详情</span>
          <p>{detail || '暂无'}</p>
        </div>
      </div>
    );
    const extraContent = (
      <div className={styles.extraContent}>
        <Search
          className={styles.extraContentSearch}
          placeholder="请输入商品名称"
          onSearch={this.handleSearch}
        />
      </div>
    );
    const Delete = props => <a onClick={() => editAndDelete(props.current, props.index)}>删除</a>;

    const getModalContent = () => {
      if (done) {
        return (
          <Result
            type="success"
            title="操作成功"
            description="已确认添加该图片"
            actions={
              <Button type="primary" onClick={this.handleDone}>
                知道了
              </Button>
            }
            className={styles.formResult}
          />
        );
      }
      // const imageUrl = this.state.imageUrl;
      return (
        <Form onSubmit={this.handleSubmit}>
          <FormItem label="商品封面尺寸" {...this.formLayout}>
            <span>1000*1000</span>
          </FormItem>
          <FormItem label="商品封面" {...this.formLayout}>
            {getFieldDecorator('imageHash', {
              rules: [{ required: false, message: '请选择商品封面' }],
              initialValue: `${current.imageHash}`,
            })(<ImageUploader />)}
            <Modal footer={null} onCancel={this.handleCancelsTop}>
              <img alt="这是头像" style={{ width: '50%' }} />
            </Modal>
          </FormItem>
          <FormItem label="商品名称" {...this.formLayout}>
            {getFieldDecorator('title', {
              rules: [{ required: true, message: '请输入商品名称', max: 15 }],
              initialValue: current.title,
            })(<Input placeholder="请输入" />)}
          </FormItem>
          <FormItem label="商品单位" {...this.formLayout}>
            {getFieldDecorator('unit', {
              rules: [{ required: true, message: '请输入商品单位', max: 15 }],
              initialValue: current.unit,
            })(<Input placeholder="请输入" />)}
          </FormItem>
          <FormItem label="价格" {...this.formLayout}>
            {getFieldDecorator('price', {
              rules: [{ required: true, message: '请输入价格' }],
              initialValue: Number(current.price) / 100,
            })(<InputNumber min={0} max={999999999} />)}
          </FormItem>
          <FormItem label="原价" {...this.formLayout}>
            {getFieldDecorator('original', {
              rules: [{ required: true, message: '请输入原价' }],
              initialValue: Number(current.original) / 100,
            })(<InputNumber min={0} max={999999999} />)}
          </FormItem>
          <FormItem label="店铺ID" {...this.formLayout}>
            {getFieldDecorator('storeId', {
              rules: [{ required: true, message: '店铺页面可查看店铺ID' }],
              initialValue: current.storeId,
            })(<InputNumber min={0} max={999999999} />)}
          </FormItem>
          <FormItem label="商品多图尺寸" {...this.formLayout}>
            <span>1000*1000</span>
          </FormItem>
          <FormItem {...this.formLayout} label="商品多图">
            {getFieldDecorator('imageHashes', {
              rules: [{ message: '请选择商品多图！', type: 'array' }],
              initialValue: `${current.imageHashes}`,
            })(<ImagesUploader />)}
            <Modal visible={previewVisible} footer={null} onCancel={this.handleCancels}>
              <img alt="example" style={{ width: '50%' }} src={previewImage} />
            </Modal>
          </FormItem>
        </Form>
      );
    };
    return (
      <PageHeaderWrapper>
        <div className={styles.standardList}>
          <Card
            className={styles.listCard}
            bordered={false}
            title="商品管理"
            style={{ marginTop: 24 }}
            bodyStyle={{ padding: '0 32px 40px 32px' }}
            extra={extraContent}
          >
            <Button
              type="dashed"
              style={{ width: '100%', marginBottom: 8 }}
              icon="plus"
              onClick={this.showModal}
              ref={component => {
                /* eslint-disable */
                this.addBtn = findDOMNode(component);
                /* eslint-enable */
              }}
            >
              添加
            </Button>
            <List
              size="large"
              rowKey="id"
              loading={loading}
              pagination={{
                ...data.pagination,
                onChange: page => {
                  const { dispatch } = this.props;
                  dispatch({
                    type: 'commodity/fetch',
                    payload: page,
                  });
                },
              }}
              dataSource={data.list.filter(item => item.status === 'selling')}
              item={data.list}
              renderItem={(item, index) => (
                <List.Item
                  actions={[
                    <a
                      onClick={e => {
                        e.preventDefault();
                        this.showEditModal(item, index);
                      }}
                    >
                      编辑
                    </a>,
                    <Delete current={item} index={index} />,
                  ]}
                >
                  <List.Item.Meta
                    avatar={
                      <Avatar src={`${imageOrigin}${item.imageHash}`} shape="square" size="large" />
                    }
                    title={`[${item.id}] ${item.title}`}
                    description={item.intro}
                  />
                  <ListContent data={item} />
                </List.Item>
              )}
            />
          </Card>
        </div>
        <Modal
          title={done ? null : `商品${current ? '添加' : '编辑'}`}
          className={styles.standardListForm}
          width={640}
          bodyStyle={done ? { padding: '72px 0' } : { padding: '28px 0 0' }}
          destroyOnClose
          visible={visible}
          {...modalFooter}
        >
          {getModalContent()}
        </Modal>
      </PageHeaderWrapper>
    );
  }
}

export default Commodity;
